//
//  ST_PushPeculiarityChildrenController.swift
//  btvideo
//
//  Created by mac on 2020/1/13.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import HandyJSON
import SwifterSwift
import SwiftyAttributes

//发布特质二级 - Controller
class ST_PushPeculiarityChildrenController: ST_BTLightBarViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        view.backgroundColor = UIColor.white

        title_nav_btn.setTitleForAllStates("选择你的特质")
        
        
        right_nav_btn.setTitleForAllStates("下一步")
        right_nav_btn.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.semibold)
        right_nav_btn.backgroundColor = Color.init(hexString: "#FEC207")
        right_nav_btn.cornerRadius = 15
        right_nav_btn.snp.remakeConstraints { (make) in
            make.right.equalTo(own_navigation_bar).offset(-15)
            make.centerY.equalTo(title_nav_btn)
            make.width.equalTo(75)
            make.height.equalTo(30)
        }
        right_nav_btn.isHidden = false
        
         
        
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.init(top: statusBarHeight+49, left: 0, bottom: 0, right: 0))
        }
        
        view.addSubview(tips_label)
        tips_label.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-12-BTSafeAreaBottom)
        }
        
        view.addSubview(tipsBtn)
        tipsBtn.snp.makeConstraints { (make) in
            make.edges.equalTo(tips_label)
        }
        
        request_data()
    }
    

    func request_data(){
        
        
        guard let willPush = willPushParentPeculiarity else {
            return
        }
        
        JVrequest(PH.peculiarityChildListApi,parameters:["feature_id":willPush.id], success: { (json) in
            
            if let list = [ST_PeculiarityModel].deserialize(from: json["data"].rawString() ?? "") as? [ST_PeculiarityModel]{
                
                self.data_array = list
                
                self.data_array.first?.isSelected = true
            }
            
            self.collectionView.reloadData()
            
            let cellHeight = self.layout.itemSize.height
            
            let gap = self.layout.minimumLineSpacing * (self.data_array.count.cgFloat - 1)
            
            let maxY = self.data_array.count.cgFloat*cellHeight + gap + statusBarHeight + 49
            
            self.tips_label.alpha = maxY < ScreenHeight - BTSafeAreaBottom - 60 ? 1 : 0
            
            if self.tips_label.alpha == 0{
                self.auto_hidden_tips = true
            }
            
            
        }) { (code, err) in
            
            ToastHud(text: err, view: self.view)
        }
        
        
        
    }
    
//    MARK: - Properties

    fileprivate lazy var layout:UICollectionViewFlowLayout = {
       let controlLayout = UICollectionViewFlowLayout()
        controlLayout.minimumLineSpacing = 7
//        controlLayout.minimumInteritemSpacing = 15
        controlLayout.sectionInset = UIEdgeInsets.init(top: 7, left: 0, bottom: 0, right: 0)
        
//        let w = (ScreenWidth - 15 * 3)/2
        
        controlLayout.itemSize = CGSize.init(width:ScreenWidth, height: 60+15)
        
        return controlLayout
    }()
    
    fileprivate lazy var collectionView:UICollectionView = {
        let control = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: self.layout)
        control.delegate = self
        control.dataSource = self
        control.register(cellWithClass: ST_PushPeculiarityChildCell.self)
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        control.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: BTSafeAreaBottom + 90, right: 0)
        
        control.alwaysBounceVertical = true
        
        control.backgroundColor = Color.white
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        return control
    }()
    
    fileprivate var auto_hidden_tips = false
    fileprivate lazy var tips_label:UILabel = {
        let control = UILabel.init()
        
        control.alpha = 0
        
        control.numberOfLines = 0
        
        let str = "没有你要添加的特质？点击".withAttributes([Attribute.font(UIFont.systemFont(ofSize: 13, weight: UIFont.Weight.regular)),Attribute.textColor(UIColor.init(hex: 0xACB4C0)!)])
        
        str.append("增加新特质".withAttributes([Attribute.font(UIFont.systemFont(ofSize: 13, weight: UIFont.Weight.medium)),Attribute.textColor(UIColor.init(hex: 0xFEC207)!)]))
        
        str.append("反馈你的意\n见，我们会仔细斟酌你的意见！".withAttributes([Attribute.font(UIFont.systemFont(ofSize: 13, weight: UIFont.Weight.regular)),Attribute.textColor(UIColor.init(hex: 0xACB4C0)!)]))

        let p = NSParagraphStyle.create_line_spacing_paragraph_style(lineSpacing: 3)
        
        p.alignment = .center
        
        str.addAttributes([Attribute.paragraphStyle(p)], range: NSRange.init(location: 0, length: str.length))
        
        control.attributedText = str
        
        return control
    }()
    
    
    fileprivate lazy var tipsBtn:UIButton = {
            
            let control = UIButton.init(type: UIButton.ButtonType.custom)
            control.addTarget(self, action: #selector(report_peculiarity_handle), for: UIControl.Event.touchUpInside)
            return control
        }()

    
    
    fileprivate lazy var data_array = [ST_PeculiarityModel]()
    
    fileprivate lazy var last_selected_item = data_array.first
    
//    MARK: - Event
    override func right_click() {
        
        guard let selected = last_selected_item else {
            return
        }
        
        willPushParentPeculiarity?.children = [selected]
        willPushPeculiarity = selected
        self.navigationController?.pushViewController(ST_PushPeculiaritySelectMediaController())
        
        
    }
    
    
    @objc fileprivate func report_peculiarity_handle(){
        
        let vc = ST_TianReportController()
        
        vc.type = .peculiarityAdvice
        
        self.navigationController?.pushViewController(vc)
        
    }
}

//MARK: -
extension ST_PushPeculiarityChildrenController:UICollectionViewDelegate,UICollectionViewDataSource{

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        if !auto_hidden_tips{
            return
        }
        
        let lastIndex = data_array.count - 1
        
        guard lastIndex >= 0 else {
            return
        }
        
        guard let cell = self.collectionView.cellForItem(at: IndexPath.init(row: lastIndex, section: 0)) else{
            return
        }
        
        let rect = self.collectionView.convert(cell.frame, to: nil)
        
        if rect.maxY < ScreenHeight - BTSafeAreaBottom - 60 {
            tips_label.alpha = 1
        }else{
            tips_label.alpha = 0
        }
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return data_array.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withClass: ST_PushPeculiarityChildCell.self, for: indexPath)
        
        if let m = data_array[safe:indexPath.item]{
            cell.model = m
        }
        
//        cell.contentView.backgroundColor = Color.random
        
        return cell
    }


    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        last_selected_item?.isSelected = false
        
        if let m = data_array[safe:indexPath.item]{
            m.isSelected = true
            last_selected_item = m
        }
        
        
        collectionView.reloadData()
        
        
        
        
        
    }

}
